<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品添加</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
      <!-- 步骤条 -->
      <el-steps :active="activeIndex-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 选项卡 -->
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" label-position="top">
      <el-tabs v-model="activeIndex" :tab-position="'left'" :before-leave="beforeTabs" @tab-click="cahngeItem">
        <!-- 步骤一 -->
        <el-tab-pane label="基本参数" name="0">
          <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model="ruleForm.goods_name"></el-input>
          </el-form-item>
          <el-form-item label="商品价格" prop="goods_price">
            <el-input type="number" v-model="ruleForm.goods_price"></el-input>
          </el-form-item>
          <el-form-item label="商品重量" prop="goods_weight">
            <el-input type="number" v-model="ruleForm.goods_weight"></el-input>
          </el-form-item>
          <el-form-item label="商品名数量" prop="goods_number">
            <el-input type="number" v-model="ruleForm.goods_number"></el-input>
          </el-form-item>
          <el-form-item label="商品分类" prop="goods_cat">
            <el-cascader
              v-model="ruleForm.goods_cat"
              :options="cateList"
              expand-trigger="hover"
              :props="cateprops"
              @change="handleChange">
            </el-cascader>
          </el-form-item>
        </el-tab-pane>
        <el-tab-pane label="商品参数" name="1">配置管理</el-tab-pane>
        <el-tab-pane label="商品属性" name="2">角色管理</el-tab-pane>
        <el-tab-pane label="商品图片" name="3">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            list-type="picture"
            :headers="headerUpload"
            :on-success="successUpload">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-tab-pane>
        <el-tab-pane label="商品内容" name="4">
          <!-- 富文本编辑器 -->
          <quill-editor ref="myTextEditor" v-model="ruleForm.goods_introduce">
          </quill-editor>
          <div class="btn">
            <el-button type="primary" @click="addItem" class="goodsAdd">添加商品</el-button>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    </el-card>
    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="previewbulr" width="50%">
      <img :src="previewPath" alt="" class="previewImg">
    </el-dialog>
  </div>
</template>
<script>
import{goodscate,getcatelist}from '@/api/login'
import _ from 'lodash'
export default {
  data(){
    return{
      // 上传图片的url地址
      uploadUrl: this.$var.domainImg,
      // 上传图片的请求头
      headerUpload:{
        Authorization:this.$api.GetStore('token')
      },
      activeIndex:'0',
      // 表单数据
      ruleForm:{
        goods_name:"",
        goods_price:0,
        goods_weight:0,
        goods_number:0,
        goods_cat:[],
        pics:[],
        goods_introduce:""
      },
      // 表单验证规则
      rules:{
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ],
        // goods_price: [
        //   { required: true, message: '请输入商品价格', trigger: 'blur' },
        //   { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        // ],
        // goods_weight: [
        //   { required: true, message: '请输入商品重量', trigger: 'blur' },
        //   { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        // ],
        // goods_number: [
        //   { required: true, message: '请输入商品数量', trigger: 'blur' },
        //   { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        // ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' },
        ],
      },
      // 商品分类数据
      cateList:[],
      // 级联选择器对象
      cateprops:{
        value:"cat_id",
        label:"cat_name",
        children:"children"
      },
      // 上传图片成功后的数据
      imgData:{},
      // 商品图片预览框是否弹出
      previewbulr:false,
      // 要预览的图片路径
      previewPath:""
    }
  },
  created(options){
    console.log(options)
    this.loadDate()
  },
  computed:{
    cateId(){
      if(this.ruleForm.goods_cat.length==3){
        return this.ruleForm.goods_cat[2]
      }
    }
  },
  methods:{
    async loadDate(){
      const{$api:{GetStore}}=this
      const res = await goodscate()
      console.log(res)
      // var arr=GetStore('token')
      // console.log(arr)
      this.cateList=res.data.data
    },
    // 级联选择器确认选择
    handleChange(item){
      console.log(item)
      if(item.length!=3){
        this.ruleForm.goods_cat=[]
      }
    },
    // 选项卡切换事件
    beforeTabs(activeName,oldActiveName){
      const{$api:{Error}}=this
      console.log(activeName,oldActiveName)
      if(this.ruleForm.goods_cat.length!=3&&this.activeIndex=='0'){
        Error("请选择商品分类")
        return false
      }
    },
    // 选项卡点击事件
    cahngeItem(){
      console.log(this.activeIndex)
      if(this.activeIndex=='1'){
        getcatelist('categories/'+this.cateId+'/attributes',{sel:'many'}).then(res=>{
          console.log(res)
        })
      }
    },
    // 处理图片预览
    handlePreview(file){
      console.log(file)
      this.previewPath=file.url 
      this.previewbulr=true
    },
    // 移出图片的操作
    handleRemove(file, fileList){
      console.log(file, fileList)
      const{pics}=this.ruleForm
      var selectIndex=0
      var filepath=file.response.data.tmp_path
      // 找到对应索引，用findIndex或者for循环遍历都可以
      const index=pics.findIndex(item=>{
        item.pic=filepath
      })
      // for(let i in pics){
      //   if(pics[i].pic==filepath){
      //     console.log(i)
      //     selectIndex=i
      //   }
      // }
      pics.splice(index,1)
    },
    // 图片上传完成后的返回数据
    successUpload(response,file,fileList){
      console.log(response)
      var imgData={
        pic:response.data.tmp_path
      }
      this.ruleForm.pics.push(imgData)
    },
    // 添加商品（表单验证）
    addItem(){
      const{$api:{Error}}=this
      this.$refs.ruleForm.validate((valid) => {
        console.log(valid)
        if(!valid){
          Error('请填写必填信息')
        }
      });
      const from=_.cloneDeep(this.ruleForm)
      console.log(from)
      from.goods_cat = from.goods_cat.join(',')
    }
  }
}
</script>
<style scoped>
.previewImg{
  width: 100%;
  height: 100%;
}
.btn{
  display: flex;
  justify-content: flex-end;
  margin: 20px 0;
}
</style>